import os
import json
from argparse import ArgumentParser

# from tqdm import tqdm
import matplotlib.pyplot as plt

class HTMLGenerater:

    def __init__(
        self, *, data_folder="", fixed_data="", **kwargs
    ):
        
        self.data_folder = data_folder
        self.fixed_data = fixed_data

        self.folder_dict = {}

        self.name_dict = {}
        self.num_dict = {}
        self.num_list = []

        self.group_dict = {}
        self.group_by = [
            ("l2=dis", 0), ("l2=dis", 1), 
            ("l2=dis", 2), ("l2=dis", 5), 
            ("l2=dis", 10), ("l2=dis", 15)
        ]

        self.statics = ["l2=dis"]
        self.statics_res = {}

        self.content = ""
        self.html_grp = {}
        self.file_freq = 50 # num of record each file

        self.statics_compute = ScalarStatics(save_dir=self.data_folder)


    def preprocess(self):

        print("start scan folder")
        self.scan_folder()
        self.sort_dict_key()
        print("finish scan folder")
        print("------------------")

        print("start group")
        self.group_data()
        print("finish group")
        print("------------------")



    def scan_folder(self):
        """
        scan the folder not start with "_"
        """

        datas = {}
        traverse_list = []

        for folder in [self.data_folder, self.fixed_data]:
            if folder == "":
                continue

            for i in os.listdir(folder):

                if i.startswith("_"):
                    continue

                path = os.path.join(folder, i)

                if os.path.isdir(path):
                    traverse_list.append(path)


        for p in traverse_list:

            for fn in os.listdir(p):
                fn_path = os.path.join(p, fn)
                fn_info = self.split_filename(fn)

                if not fn_info["name"] in datas:
                    datas[fn_info["name"]] = {}

                if fn_info["bn"] == "":
                    datas[fn_info["name"]][fn_info["num"]] = fn_path
                    continue

                if not fn_info["num"] in datas[fn_info["name"]]:
                    datas[fn_info["name"]][fn_info["num"]] = {}

                if fn_info["suffix"] == "":
                    datas[fn_info["name"]][fn_info["num"]][fn_info["bn"]] = fn_path
                    continue

                if not fn_info["bn"] in datas[fn_info["name"]][fn_info["num"]]:
                    datas[fn_info["name"]][fn_info["num"]][fn_info["bn"]] = {}

                datas[fn_info["name"]][fn_info["num"]][fn_info["bn"]][fn_info["suffix"]] = fn_path

        self.folder_dict = datas


    # TODO dict to sample_number 2 data (read json is needed)
    def sort_dict_key(self):

        for k in self.folder_dict:

            if not k in self.name_dict:
                self.name_dict[k] = None


            for num in self.folder_dict[k]:
                num_n = int(num)

                if not num_n in self.num_dict:
                    self.num_list.append(num_n)
                    self.num_dict[num_n] = 0

                if type(self.folder_dict[k][num]) != dict:
                    continue


                for bn in self.folder_dict[k][num]:
                    bn_num = int(bn)

                    if bn_num > self.num_dict[num_n]:
                        self.num_dict[num_n] = bn_num

                    if type(self.folder_dict[k][num][bn]) != dict:
                        continue


                    if self.name_dict[k] == None:
                        self.name_dict[k] = set()

                    for suffix in self.folder_dict[k][num][bn]:
                        self.name_dict[k].add(suffix)


        self.num_list.sort()
        for k in self.name_dict:
            if type(self.name_dict[k]) == set:
                suffixs = list(self.name_dict[k])
                suffixs.sort()
                self.name_dict[k] = suffixs


        # open the jsons
        scalar = self.folder_dict["scalar"]
        new_dict = {}

        for fn in scalar.values():
            with open(fn) as fp:
                data = json.load(fp)

            for names, val in data.items():
                name_dict = self.split_filename(names)
                num = int(name_dict["num"]) 
                bn_num = int(name_dict["bn"])

                if not name_dict["name"] in new_dict:
                    new_dict[name_dict["name"]] = {}

                if not name_dict["num"] in new_dict[name_dict["name"]]:
                    new_dict[name_dict["name"]][name_dict["num"]] = {}

                new_dict[name_dict["name"]][name_dict["num"]][name_dict["bn"]] = val

        # update
        self.folder_dict.pop("scalar")
        self.folder_dict.update(new_dict)
        self.name_dict.pop("scalar")
        
        for k in new_dict:
            self.name_dict[k] = None


    def split_filename(self, fn):
        """
        Input: fn, Output: {"name": attribution, "num": batch num, "bn": iter num, "suffix": suffix}
        """
        fn = os.path.splitext(fn)[0]
        tmp = fn.split("-")

        dict_ = {
            "name" : tmp[0], 
            "num" : tmp[1]
        }

        if len(tmp) == 4:
            dict_["bn"] = tmp[2]
            dict_["suffix"] = tmp[3]
        elif len(tmp) == 3:
            dict_["bn"] = tmp[2]
            dict_["suffix"] = ""
        else:
            dict_["bn"] = ""
            dict_["suffix"] = ""

        return dict_


    def group_data(self):

        self.group_dict = {}
        for g in self.group_by:
            self.group_dict[str(g[1])] = {"description" : g[0]+"<="+str(g[1])}
        self.group_dict["other"] = {
            "description" : g[0]+">"+str(self.group_by[-1][1])
        }

        for iter_ in self.num_list:

            bn_num = self.num_dict[iter_]
            for b in range(1, bn_num+1):

                iter_s, bn_s = str(iter_), str(b)
                flag = False
                for g in self.group_by:
                    ind, thresh = g
                    t_s = str(thresh)

                    if self.folder_dict[ind][iter_s][bn_s] <= thresh:

                        if not iter_s in self.group_dict[t_s]:
                            self.group_dict[t_s][iter_s] = set()

                        self.group_dict[t_s][iter_s].add(bn_s)

                        flag = True
                        break
                
                if not flag:

                    if not iter_s in self.group_dict["other"]:
                        self.group_dict["other"][iter_s] = set()

                    self.group_dict["other"][iter_s].add(bn_s)


        for k in self.group_dict:
            tmp = list(filter(
                lambda x : x != "description", self.group_dict[k].keys()
            ))
            tmp = sorted(tmp, key=lambda x: int(x))
            self.group_dict[k]["list"] = tmp

            for i in self.group_dict[k]["list"]:
                tmp = list(self.group_dict[k][i])
                tmp = sorted(tmp, key=lambda x: int(x))
                self.group_dict[k][i] = tmp


    def generate_html(self):
    
        self.content = ""
        self.html_grp = {}


        for grp in self.group_dict.values():

            des = grp["description"]
            cnt = 0
            for iteration in grp["list"]:
                bn = grp[iteration]

                for i in bn:

                    info_dict = {
                        "iter" : int(iteration), 
                        "bn" : int(i)
                    }

                    try:
                        tmp_k = list(self.name_dict.keys())[0]
                        tmp_ = self.folder_dict[tmp_k][iteration][i]
                    except KeyError:
                        # print(list(self.name_dict.keys())[0], iteration, i)
                        continue

                    for k, v in self.name_dict.items():
                        
                        if v == None:
                            info_dict[k] = self.folder_dict[k][iteration][i]
                            continue

                        for s in v:
                            info_dict["-".join([k, s])] = \
                                self.folder_dict[k][iteration][i][s]

                    self.content += self.append_html(**info_dict)
                    cnt += 1

                    if cnt >= self.file_freq:
                        self.save_html(prefix=des)
                        cnt = 0

                    
            self.save_html(prefix=des)

        # for iteration in self.num_list:
        #     batch_size = self.num_dict[iteration]
        #     iter_str = str(iteration)

        #     for i in range(1, batch_size+1):
        #         i_str = str(i)
        #         info_dict = {
        #             "iter" : iteration, 
        #             "bn" : i
        #         }

        #         for k, v in self.name_dict.items():
                    
        #             if v == None:
        #                 info_dict[k] = self.folder_dict[k][iter_str][i_str]
        #                 continue

        #             for s in v:
        #                 info_dict["-".join([k, s])] = self.folder_dict[k][iter_str][i_str][s]

        #         self.append_html(**info_dict)
        #         cnt += 1

        #         if cnt >= self.file_freq:
        #             self.save_html()
        #             cnt = 0

                    
        # self.save_html()
        self.generate_index_html()


    def generate_index_html(self):

        context = " \n<!DOCTYPE HTML> \n<html> \n<head> \n</head> \n\n<body>\n\n"


        for grp_des, grp in self.html_grp.items():
            context += "<h2> {} </h2>\n".format(grp_des)

            for ids, url in enumerate(grp):
                context += f"<a href=\"{url}\">from {ids*self.file_freq+1} to {(ids+1)*self.file_freq} </a> <br>"

        # for ids, url in enumerate(self.html_grp):
        #     context += f"<a href=\"{url}\">from {ids*self.file_freq+1} to {(ids+1)*self.file_freq} </a> <br>"

        
        for k, v in self.statics_res.items():
            context += "<h2> {} - statics </h2>\n".format(k)

            context += "\t<img src=\"{}\"/>\n".format(v["img"])

            st_data = v["data"]
            res_str = ""
            res_str += "\t<br>results of datasets is :<br>\n"

            res_str += "\t<table border=\"1\">"
            for i, n, r in zip(
                st_data["intervals"], st_data["nums"], st_data["rates"]
            ):
                res_str += "\t\t<tr>\t<td>{}</td> <td>{}</td> <td>{:.2f}%</td>\t</tr>\n".format(i, n, r*100)
            res_str += "\t</table>"
            
            res_str += "\tmax dis is {:.2f}<br>\n".format(st_data["max"])
            context += res_str


        context += " \n</body> \n</html>\n"

        fn = os.path.join(self.data_folder, "index.html")

        with open(fn, "w") as fp:
            fp.write(context)


    def save_html(self, prefix="samples"):

        if self.content == "":
            return
        
        self.content = self.begin_html() + self.content

        self.content = self.content + self.end_html()


        if not prefix in self.html_grp:
            self.html_grp[prefix] = []

        nums = len(self.html_grp[prefix])
        fn = f"{prefix}_{nums*self.file_freq+1}_to_{(nums+1)*self.file_freq}.html"
        # print(prefix)
        if "<" in fn or ">" in fn:
            fn = fn.replace("<=", "_le_")
            fn = fn.replace(">=", "_gt_")
            fn = fn.replace("<", "_le_")
            fn = fn.replace(">", "_gt_")
        fn = os.path.join(self.data_folder, fn)

        with open(fn, "w") as fp:
            fp.write(self.content)

        self.content = ""
        self.html_grp[prefix].append(fn)


    def begin_html(self):

        begin = " \n<!DOCTYPE HTML> \n<html> \n<head> \n</head> \n\n<body>\n\n"

        return begin


    def end_html(self):

        end = " \n</body> \n</html>\n"

        return end


    def append_html(self, **kwargs):

        info = kwargs.copy()

        attr_list1 = [["sar=img", "opt=img"], ["gt=map", "corr=map-ch1"]]
        attr_list3 = ["l2=dis", "loc"]
        attr_list4 = [
            ["sar=mft-ch1", "sar=mft-ch2", "sar=mft-ch3", "sar=mft-ch4", "sar=mft-ch5"], 
            ["opt=mft-ch1", "opt=mft-ch2", "opt=mft-ch3", "opt=mft-ch4", "opt=mft-ch5"], 
            ["sar=mft-ch6", "sar=mft-ch7", "sar=mft-ch8", "sar=mft-ch9"], 
            ["opt=mft-ch6", "opt=mft-ch7", "opt=mft-ch8", "opt=mft-ch9"]
        ]

        # attr_list1 = [["sar=img", "opt=img"], ["gt=map", "corr=map-ch1"]]
        # attr_list3 = ["l2=dis", "loc"]
        # attr_list4 = [
        #     ["sar=mft-ch1", "sar=mft-ch2", "sar=mft-ch3", "sar=mft-ch4", "sar=mft-ch5"], 
        #     ["sar=mft-ch6", "sar=mft-ch7", "sar=mft-ch8", "sar=mft-ch9"], 
        #     ["gt=mask", "sar=mask"]
        # ]

        # attr_list1 = [["sar=img", "opt=img"], ["gt=map", "corr=map-ch1"]]
        # attr_list3 = ["l2=dis", "loc"]
        # attr_list4 = [
        #     ["mask=map-ch1"], 
        #     ["sar=mft-ch1", "sar=mft-ch2", "sar=mft-ch3", "sar=mft-ch4", "sar=mft-ch5"], 
        #     ["opt=mft-ch1", "opt=mft-ch2", "opt=mft-ch3", "opt=mft-ch4", "opt=mft-ch5"], 
        #     ["sar=mft-ch6", "sar=mft-ch7", "sar=mft-ch8", "sar=mft-ch9"], 
        #     ["opt=mft-ch6", "opt=mft-ch7", "opt=mft-ch8", "opt=mft-ch9"]
        # ]
        
        add = "<h2> iter {} bn {} </h2>\n".format(info["iter"], info["bn"])

        str_content = ""

        str_content += add
        
        # patch show
        for attr in attr_list1:
            tmp = " + ".join(attr)
            add = "\t<h3> {} </h3>\n".format(tmp)

            add += "\t<div>\n"
            for elem in attr:
                add += "\t\t<img src=\"{}\"/>\n".format(info[elem])
            add += "\t</div>"

            str_content += add
        
        # scalar show
        add = "\t<h3> metrics </h3>\n"
        add += "\t<table border=\"1\">\n"

        for attr in attr_list3:
            add += "\t\t<tr>\n\t\t\t<td> {} </td> <td> {} </td>\n\t\t</tr>\n".format(attr, info[attr])
            
        add += "\t</table>\n"
        str_content += add

        # feature map show
        for attr in attr_list4:
            tmp = " + ".join(attr)
            add = "\t<h3> {} </h3>\n".format(tmp)

            add += "\t<div>\n"
            for elem in attr:
                add += "\t\t<img src=\"{}\"/>\n".format(info[elem])
            add += "\t</div>"

            str_content += add

        return str_content


    def get_statics(self):
        # pass
        print("start statics by {}".format(self.statics))


        data_seq = []
        for s in self.statics:
            data_dict = self.folder_dict[s]
            for i in data_dict.values():
                for j in i.values():
                    data_seq.append(j)

            # ss = ScalarStatics(save_dir=self.data_folder)
            ss = self.statics_compute
            st_data, img_addr = ss.get_data(data_seq)
            print(st_data)
            self.statics_res[s] = {
                "img" : img_addr, 
                "data" : st_data
            }

            data_seq.clear()

            res_str = ""
            res_str += "results of datasets is :\n"

            for i, n, r in zip(
                st_data["intervals"], st_data["nums"], st_data["rates"]
            ):
                res_str += "|{}\t|{}\t|{:.2f}%\t|\n".format(i, n, r*100)
            
            res_str += "max dis is {}\n".format(st_data["max"])
            res_str += "img saved as {}".format(img_addr)
            print(res_str)


        print("end statics")
        print("------------------")


class ScalarStatics:

    def __init__(self, max_val=15, save_dir="", **kwargs):
        """
        """
        self.scalar = None
        self.save_dir = save_dir
        self.max_val = max_val
        self.num = 0
        self.data = {"nums": [], "rates": [], "max": 0, "intervals": []}
        self.pic = ""


    def compute(self):

        self.num = len(self.scalar)
        self.data["nums"].extend([0]*(self.max_val+2))
        self.data["rates"].extend([0]*(self.max_val+2))
        self.data["max"] = max(self.scalar)
        self.data["intervals"].extend(
            list(map(lambda x: "<="+str(x), range(self.max_val+1)))
        )
        self.data["intervals"].append(">"+str(self.max_val))

        for s in self.scalar:

            if s > self.max_val:
                self.data["nums"][self.max_val+1] += 1
                continue

            for thresh in range(self.max_val+1):
                ids = thresh

                if s <= thresh:
                    self.data["nums"][ids] += 1
                    break


        for ids, n in enumerate(self.data["nums"]):
            self.data["rates"][ids] = n / self.num


    def draw_pic(self):

        y_label = self.data["intervals"]
        x_label = self.data["nums"]
        texts = list(map(
            lambda x: "{:.2f}% {}".format(x[0]*100, x[1]), 
            zip(self.data["rates"], self.data["nums"])
        ))

        plt.barh(y_label, x_label, align='center', color='steelblue', alpha=0.8)
        plt.xlabel('nums of samples')
        plt.title('sample distribution in intervals')
        plt.xlim([0, max(x_label)*1.2])

        for x,(y,t) in enumerate(zip(x_label, texts)):
            plt.text(y, x, t, va='center_baseline')

        # plt.show()
        self.pic = os.path.join(self.save_dir, "statics.png")
        plt.savefig(self.pic)


    def get_data(self, scalar):

        self.scalar = scalar

        self.compute()
        self.draw_pic()
        
        return self.data, self.pic


class InTurnHTMLGenerator(HTMLGenerater):


    def __init__(self, *, data_folder="", fixed_data="", **kwargs):
        super(InTurnHTMLGenerator, self).__init__(
            data_folder=data_folder, fixed_data=fixed_data, **kwargs
        )

        self.content_inturn = ""


    def generate_html(self):
        super(InTurnHTMLGenerator, self).generate_html()
        
        self.html_inturn = []

        bn_finish_flag = False
        for iter_ids in map(str, range(1, 10000)):

            batch_info = []
            iter_finish_flag = False
            for bn_ids in map(str, range(1, 10000)):

                info_dict = {
                    "iter" : int(iter_ids), 
                    "bn" : int(bn_ids)
                }

                for k, v in self.name_dict.items():

                    if iter_ids not in self.folder_dict[k]:
                        bn_finish_flag = True
                        break
                    if bn_ids not in self.folder_dict[k][iter_ids]:
                        iter_finish_flag = True
                        break
                        
                    if v == None:
                        info_dict[k] = self.folder_dict[k][iter_ids][bn_ids]
                        continue

                    for s in v:
                        info_dict["-".join([k, s])] = \
                            self.folder_dict[k][iter_ids][bn_ids][s]

                if iter_finish_flag or bn_finish_flag:
                    break

                batch_info.append(info_dict.copy())

            if bn_finish_flag:
                break

            for info in batch_info:
                self.content_inturn += self.append_html(**info)

            self.save_inturn_html(iter_ids=iter_ids)

        self.generate_inturn_index_html()


    def save_inturn_html(self, prefix="inturn", iter_ids="0"):

        if self.content_inturn == "":
            return
        
        self.content_inturn = self.begin_html() + self.content_inturn
        self.content_inturn = self.content_inturn + self.end_html()

        fn = f"{prefix}_Iter{iter_ids}.html"
        fn = os.path.join(self.data_folder, fn)

        with open(fn, "w") as fp:
            fp.write(self.content_inturn)

        self.content_inturn = ""
        self.html_inturn.append(fn)


    def generate_inturn_index_html(self):

        context = " \n<!DOCTYPE HTML> \n<html> \n<head> \n</head> \n\n<body>\n\n"


        for fn in self.html_inturn:
        
            url = fn
            kw = os.path.splitext(
                os.path.basename(fn)
            )[0]
            context += f"<a href=\"{url}\">from {kw} </a> <br>"

        context += " \n</body> \n</html>\n"

        fn = os.path.join(self.data_folder, "index_inturn.html")

        with open(fn, "w") as fp:
            fp.write(context)


class NegScalarStatics(ScalarStatics):


    def __init__(self, group=None, save_dir="", **kwargs):
        self.scalar = None
        self.save_dir = save_dir
        self.group = [
            0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1
        ] if group is None else group
        self.num = 0
        self.data = {"nums": [], "rates": [], "max": 0, "intervals": []}
        self.pic = ""


    def compute(self):

        self.num = len(self.scalar)
        self.data["nums"].extend([0]*(len(self.group)+1))
        self.data["rates"].extend([0]*(len(self.group)+1))
        self.data["max"] = max(self.scalar)
        self.data["intervals"].extend(
            list(map(lambda x: ">="+str(x), self.group))
        )
        self.data["intervals"].append("<"+str(self.group[len(self.group)-1]))

        for s in self.scalar:

            count_flag = False

            for ids, thresh in enumerate(self.group):

                if s >= thresh:
                    self.data["nums"][ids] += 1
                    count_flag = True
                    break

            if not count_flag:
                self.data["nums"][len(self.group)] += 1


        for ids, n in enumerate(self.data["nums"]):
            self.data["rates"][ids] = n / self.num


class DespeckleInTurnHTMLGenerator(InTurnHTMLGenerator):


    def __init__(self, *, data_folder="", fixed_data="", **kwargs):
        super().__init__(data_folder=data_folder, fixed_data=fixed_data, **kwargs)

        # self.group_by = [
        #     ("SSIM", 0.8), ("SSIM", 0.6), 
        #     ("SSIM", 0.4), ("SSIM", 0.2),
        # ]

        # self.statics = ["SSIM"]

        self.group_by = [("ENL", 1.0)]

        self.statics = ["ENL"]
        self.statics_compute = NegScalarStatics(save_dir=self.data_folder)


    def append_html(self, **kwargs):

        info = kwargs.copy()
        

        attr_list1 = [["patch=img"]]
        # attr_list3 = ["SSIM", "PSNR"]
        attr_list3 = ["ENL"]
        attr_list4 = [["despeckle=img", "normal=img"], ["noisy=img"]]
        
        add = "<h2> iter {} bn {} </h2>\n".format(info["iter"], info["bn"])

        str_content = ""

        str_content += add
        
        # patch show
        for attr in attr_list1:
            tmp = " + ".join(attr)
            add = "\t<h3> {} </h3>\n".format(tmp)

            add += "\t<div>\n"
            for elem in attr:
                add += "\t\t<img src=\"{}\"/>\n".format(info[elem])
            add += "\t</div>"

            str_content += add
        
        # scalar show
        add = "\t<h3> metrics </h3>\n"
        add += "\t<table border=\"1\">\n"

        for attr in attr_list3:
            add += "\t\t<tr>\n\t\t\t<td> {} </td> <td> {} </td>\n\t\t</tr>\n".format(attr, info[attr])
            
        add += "\t</table>\n"
        str_content += add

        # feature map show
        for attr in attr_list4:
            tmp = " + ".join(attr)
            add = "\t<h3> {} </h3>\n".format(tmp)

            add += "\t<div>\n"
            for elem in attr:
                add += "\t\t<img src=\"{}\"/>\n".format(info[elem])
            add += "\t</div>"

            str_content += add

        return str_content


    def group_data(self):

        self.group_dict = {}
        for g in self.group_by:
            self.group_dict[str(g[1])] = {"description" : g[0]+">="+str(g[1])}
        self.group_dict["other"] = {
            "description" : g[0]+"<"+str(self.group_by[-1][1])
        }

        for iter_ in self.num_list:

            bn_num = self.num_dict[iter_]
            for b in range(1, bn_num+1):

                iter_s, bn_s = str(iter_), str(b)
                flag = False

                try:
                    tmp_ = self.folder_dict[self.group_by[0][0]][iter_s][bn_s]
                except KeyError:
                    continue

                for g in self.group_by:
                    ind, thresh = g
                    t_s = str(thresh)
                    

                    if self.folder_dict[ind][iter_s][bn_s] >= thresh:

                        if not iter_s in self.group_dict[t_s]:
                            self.group_dict[t_s][iter_s] = set()

                        self.group_dict[t_s][iter_s].add(bn_s)

                        flag = True
                        break
                
                if not flag:

                    if not iter_s in self.group_dict["other"]:
                        self.group_dict["other"][iter_s] = set()

                    self.group_dict["other"][iter_s].add(bn_s)


        for k in self.group_dict:
            tmp = list(filter(
                lambda x : x != "description", self.group_dict[k].keys()
            ))
            tmp = sorted(tmp, key=lambda x: int(x))
            self.group_dict[k]["list"] = tmp

            for i in self.group_dict[k]["list"]:
                tmp = list(self.group_dict[k][i])
                tmp = sorted(tmp, key=lambda x: int(x))
                self.group_dict[k][i] = tmp


def parser():
    parser = ArgumentParser()
    parser.add_argument(
        '-f', '--folder', help='the folder under which the data save', default=""
    )
    parser.add_argument(
        '-d', '--default_folder', help='the folder under which the org data (such as patch and gt map) save', default=""
    )
    args = parser.parse_args()

    return args


if __name__ == "__main__1":

    data_folder = "E:/datasets/client-data/2022-12-07-&-17-04-25"

    HG = HTMLGenerater(data_folder=data_folder)
    
    print(HG.name_dict)
    # print(HG.num_dict)
    # print(HG.num_list)

    with open("./log.json", "w") as fp:
        json.dump(HG.folder_dict, fp, indent='\t', sort_keys=True)


# test ScalarStatics
if __name__ == "__main__1":

    import random

    a = list(map(lambda x: random.randint(0, 16), range(100)))
    a.sort()

    # print(a)

    ss = ScalarStatics(a, save_dir="E:\datasets\client-data\statics")


# test HTMLGenerater
if __name__ == "__main__1":

    args = parser()

    # data_folder = "E:/datasets/client-data/2022-12-07-&-17-04-25"
    data_folder = args.folder
    fixed_data = args.default_folder

    HG = HTMLGenerater(data_folder=data_folder, fixed_data=fixed_data)
    
    HG.preprocess()
    HG.get_statics()
    # HG.group_data()
    HG.generate_html()


# test InTurnHTMLGenerator
if __name__ == "__main__":

    args = parser()

    # data_folder = "E:/datasets/client-data/2022-12-07-&-17-04-25"
    data_folder = args.folder
    fixed_data = args.default_folder

    HG = InTurnHTMLGenerator(data_folder=data_folder, fixed_data=fixed_data)

    HG.preprocess()
    HG.get_statics()
    HG.generate_html()


# test DespeckleInTurnHTMLGenerator
if __name__ == "__main__1":

    args = parser()

    # data_folder = "E:/datasets/client-data/2022-12-07-&-17-04-25"
    data_folder = args.folder
    fixed_data = args.default_folder

    HG = DespeckleInTurnHTMLGenerator(data_folder=data_folder, fixed_data=fixed_data)

    HG.preprocess()
    HG.get_statics()
    HG.generate_html()


if __name__ == "__main__1":

    args = parser()

    data_folder = args.folder
    fixed_data = args.default_folder

    HG = HTMLGenerater(data_folder=data_folder, fixed_data=fixed_data)
    HG.preprocess()

    folder = "E:/workspace/SOMatch/tmp"
    with open(os.path.join(folder, "folder.json"), "w") as fp:
        json.dump(
            HG.folder_dict, fp, indent="\t", sort_keys=True)
    with open(os.path.join(folder, "name.json"), "w") as fp:
        json.dump(
            HG.name_dict, fp, indent="\t", sort_keys=True)
